Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
import numpy as np
from sklearn.datasets import load_files
#np.random.seed(1337) 
from keras.utils import np_utils
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('/data/dog_images/train')
valid_files, valid_targets = load_dataset('/data/dog_images/valid')
test_files, test_targets = load_dataset('/data/dog_images/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("/data/dog_images/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [2]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("/data/lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [3]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [4]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

>

  • 100% of the first 100 images in human_files have a detected human face.
  • 11% of the first 100 images in dog_files have a detected human face.

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

> The requirement of having a clear view of a face can be one of the criteria at the intial stage of developing the app. In the data provided above, the face detector detects human faces in 11% of first 100 images of the dog files. Clearly, the current face detector isn't ideal at the production level since it requires a clear view of a face and thus potentially risking a frustraing expereince for customers. To improve the performance of the face detector, we should build a CNN that is specifically designed to detect human faces. To accomplish this goal, we would need a large dataset of images taken from various angles with different lighting to train our network. It would also be great if these images include parital obscurations (people wearing sunglasses).

.................................................................

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [5]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.

human_files_detected_human = np.average([face_detector(img) for img in human_files_short])
dog_files_detected_human = np.average([face_detector(img) for img in dog_files_short])


print ("Propotion of human_files that have a detected human face: {}".format(human_files_detected_human))
print ("Propotion of dog_files that have a detected human face: {}".format(dog_files_detected_human))
Propotion of human_files that have a detected human face: 1.0
Propotion of dog_files that have a detected human face: 0.11
In [6]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [7]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [8]:
from keras.preprocessing import image                  
from tqdm import tqdm

#### can define the size of the input image here for a more generalizable use.
#img_width, img_height = 224, 224
####

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [9]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [10]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

>

  • 0 % of images in human_files_short detected a dog.
  • 100 % of images in dog_files_short detected a dog.
In [11]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

human_files_detected_dog = np.sum([dog_detector(img) for img in human_files_short])
dog_files_detected_dog = np.sum([dog_detector(img) for img in dog_files_short])

print ("{} % of images in human_files_short detected a dog.".format(human_files_detected_dog))
print ("{} % of images in dog_files_short detected a dog.".format(dog_files_detected_dog))
0 % of images in human_files_short detected a dog.
100 % of images in dog_files_short detected a dog.

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [12]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [01:26<00:00, 52.59it/s] 
100%|██████████| 835/835 [00:09<00:00, 85.94it/s] 
100%|██████████| 836/836 [00:09<00:00, 86.23it/s] 
In [13]:
'''
NOTE: the input size is train_tensors.shape[1:]
'''
print ("Shape of train_tensors: {}".format(train_tensors.shape))
print ("Shape of valid_tensors: {}".format(valid_tensors.shape))
print ("Shape of test_tensors: {}".format(test_tensors.shape))
Shape of train_tensors: (6680, 224, 224, 3)
Shape of valid_tensors: (835, 224, 224, 3)
Shape of test_tensors: (836, 224, 224, 3)
In [ ]:
 

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

>

  • I included 4 convolutional (conv) layers with 4 max pooling layers in between them. In each of the conv layers, filters were used 8, 16, 32, 64. To reduce the dimensionality, max pooling layer is added after each conv layer.
  • Dropout layer was added along with flattening layer before the fully connected layer to reduce the overfitting problem. Since fully connected layer only accepts row vector, flattening layer was added to convert the matrix to the row vector.
  • Except for the last layer, relu activation function was used for all the other layers. Relu was chosen since it performs well for image classification task. In the last layer, which is the fully connected layer, softmax activation function was used to produce probabilities of the prediction for each of the 133 breed (# of nodes).
In [14]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.

'''
NOTE: different ways to represent the input_shape
input_shape = (img_width, img_height, 3) 
input_shape=(224, 224, 3)
input_shape=train_tensors.shape[1:]
'''

model.add(Conv2D(8, (2,2), activation='relu', input_shape=train_tensors.shape[1:]))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(16, (2, 2), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (2, 2), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (2, 2), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Dropout(0.4))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.4))

model.add(Dense(133, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 223, 223, 8)       104       
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 111, 111, 8)       0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 110, 110, 16)      528       
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 55, 55, 16)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 54, 54, 32)        2080      
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 27, 27, 32)        0         
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 26, 26, 64)        8256      
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 13, 13, 64)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 13, 13, 64)        0         
_________________________________________________________________
flatten_2 (Flatten)          (None, 10816)             0         
_________________________________________________________________
dense_1 (Dense)              (None, 512)               5538304   
_________________________________________________________________
dropout_2 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               68229     
=================================================================
Total params: 5,617,501
Trainable params: 5,617,501
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [15]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [16]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 10

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.7973 - acc: 0.0207Epoch 00001: val_loss improved from inf to 4.57015, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 19s 3ms/step - loss: 4.7973 - acc: 0.0207 - val_loss: 4.5701 - val_acc: 0.0527
Epoch 2/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.2879 - acc: 0.0622Epoch 00002: val_loss improved from 4.57015 to 4.17388, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 18s 3ms/step - loss: 4.2871 - acc: 0.0621 - val_loss: 4.1739 - val_acc: 0.0778
Epoch 3/10
6660/6680 [============================>.] - ETA: 0s - loss: 3.8728 - acc: 0.1131Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 18s 3ms/step - loss: 3.8729 - acc: 0.1129 - val_loss: 4.2307 - val_acc: 0.0790
Epoch 4/10
6660/6680 [============================>.] - ETA: 0s - loss: 3.4749 - acc: 0.1854Epoch 00004: val_loss improved from 4.17388 to 4.03107, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 18s 3ms/step - loss: 3.4764 - acc: 0.1850 - val_loss: 4.0311 - val_acc: 0.0910
Epoch 5/10
6660/6680 [============================>.] - ETA: 0s - loss: 3.0274 - acc: 0.2748Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 18s 3ms/step - loss: 3.0272 - acc: 0.2749 - val_loss: 4.0773 - val_acc: 0.1042
Epoch 6/10
6660/6680 [============================>.] - ETA: 0s - loss: 2.5387 - acc: 0.3679Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 18s 3ms/step - loss: 2.5382 - acc: 0.3683 - val_loss: 4.2632 - val_acc: 0.0958
Epoch 7/10
6660/6680 [============================>.] - ETA: 0s - loss: 2.0744 - acc: 0.4718Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 18s 3ms/step - loss: 2.0750 - acc: 0.4717 - val_loss: 4.5671 - val_acc: 0.0994
Epoch 8/10
6660/6680 [============================>.] - ETA: 0s - loss: 1.6652 - acc: 0.5661Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 18s 3ms/step - loss: 1.6649 - acc: 0.5660 - val_loss: 5.0122 - val_acc: 0.1030
Epoch 9/10
6660/6680 [============================>.] - ETA: 0s - loss: 1.3123 - acc: 0.6458Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 18s 3ms/step - loss: 1.3112 - acc: 0.6463 - val_loss: 5.1389 - val_acc: 0.1198
Epoch 10/10
6660/6680 [============================>.] - ETA: 0s - loss: 1.0737 - acc: 0.7090Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 18s 3ms/step - loss: 1.0733 - acc: 0.7091 - val_loss: 5.5969 - val_acc: 0.1186
Out[16]:
<keras.callbacks.History at 0x7f0eea374748>

Load the Model with the Best Validation Loss

In [17]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [18]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 8.7321%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [19]:
bottleneck_features = np.load('/data/bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [20]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 512)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [21]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [22]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6620/6680 [============================>.] - ETA: 0s - loss: 12.2152 - acc: 0.1270Epoch 00001: val_loss improved from inf to 10.44518, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 308us/step - loss: 12.1917 - acc: 0.1281 - val_loss: 10.4452 - val_acc: 0.2347
Epoch 2/20
6620/6680 [============================>.] - ETA: 0s - loss: 9.8948 - acc: 0.2908Epoch 00002: val_loss improved from 10.44518 to 9.78666, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 257us/step - loss: 9.8953 - acc: 0.2910 - val_loss: 9.7867 - val_acc: 0.2994
Epoch 3/20
6640/6680 [============================>.] - ETA: 0s - loss: 9.3381 - acc: 0.3654Epoch 00003: val_loss improved from 9.78666 to 9.57058, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 258us/step - loss: 9.3394 - acc: 0.3650 - val_loss: 9.5706 - val_acc: 0.3413
Epoch 4/20
6640/6680 [============================>.] - ETA: 0s - loss: 9.1495 - acc: 0.3953Epoch 00004: val_loss improved from 9.57058 to 9.50460, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 258us/step - loss: 9.1474 - acc: 0.3955 - val_loss: 9.5046 - val_acc: 0.3329
Epoch 5/20
6660/6680 [============================>.] - ETA: 0s - loss: 9.0010 - acc: 0.4075Epoch 00005: val_loss improved from 9.50460 to 9.19098, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 257us/step - loss: 9.0028 - acc: 0.4072 - val_loss: 9.1910 - val_acc: 0.3509
Epoch 6/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.6975 - acc: 0.4268Epoch 00006: val_loss improved from 9.19098 to 9.06216, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 260us/step - loss: 8.6913 - acc: 0.4272 - val_loss: 9.0622 - val_acc: 0.3689
Epoch 7/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.5879 - acc: 0.4480Epoch 00007: val_loss improved from 9.06216 to 9.05141, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 259us/step - loss: 8.5775 - acc: 0.4488 - val_loss: 9.0514 - val_acc: 0.3689
Epoch 8/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.5182 - acc: 0.4552Epoch 00008: val_loss improved from 9.05141 to 8.96181, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 259us/step - loss: 8.5131 - acc: 0.4554 - val_loss: 8.9618 - val_acc: 0.3737
Epoch 9/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.4646 - acc: 0.4612Epoch 00009: val_loss improved from 8.96181 to 8.90401, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 258us/step - loss: 8.4534 - acc: 0.4618 - val_loss: 8.9040 - val_acc: 0.3892
Epoch 10/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.4237 - acc: 0.4683Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 2s 258us/step - loss: 8.4251 - acc: 0.4681 - val_loss: 8.9229 - val_acc: 0.3868
Epoch 11/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.4071 - acc: 0.4686Epoch 00011: val_loss improved from 8.90401 to 8.86475, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 259us/step - loss: 8.3928 - acc: 0.4693 - val_loss: 8.8647 - val_acc: 0.3844
Epoch 12/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.0059 - acc: 0.4780Epoch 00012: val_loss improved from 8.86475 to 8.44741, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 258us/step - loss: 8.0085 - acc: 0.4777 - val_loss: 8.4474 - val_acc: 0.4108
Epoch 13/20
6580/6680 [============================>.] - ETA: 0s - loss: 7.7845 - acc: 0.5012Epoch 00013: val_loss improved from 8.44741 to 8.36867, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 259us/step - loss: 7.7774 - acc: 0.5018 - val_loss: 8.3687 - val_acc: 0.4144
Epoch 14/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.7409 - acc: 0.5080Epoch 00014: val_loss improved from 8.36867 to 8.35128, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 258us/step - loss: 7.7317 - acc: 0.5087 - val_loss: 8.3513 - val_acc: 0.4228
Epoch 15/20
6640/6680 [============================>.] - ETA: 0s - loss: 7.6591 - acc: 0.5155Epoch 00015: val_loss improved from 8.35128 to 8.28188, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 255us/step - loss: 7.6751 - acc: 0.5145 - val_loss: 8.2819 - val_acc: 0.4180
Epoch 16/20
6600/6680 [============================>.] - ETA: 0s - loss: 7.6411 - acc: 0.5183Epoch 00016: val_loss improved from 8.28188 to 8.24630, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 256us/step - loss: 7.6321 - acc: 0.5189 - val_loss: 8.2463 - val_acc: 0.4335
Epoch 17/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.5994 - acc: 0.5240Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 253us/step - loss: 7.6079 - acc: 0.5235 - val_loss: 8.3462 - val_acc: 0.4251
Epoch 18/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.5813 - acc: 0.5233Epoch 00018: val_loss improved from 8.24630 to 8.23040, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 256us/step - loss: 7.5929 - acc: 0.5226 - val_loss: 8.2304 - val_acc: 0.4299
Epoch 19/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.4635 - acc: 0.5273Epoch 00019: val_loss improved from 8.23040 to 8.04874, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 255us/step - loss: 7.4565 - acc: 0.5277 - val_loss: 8.0487 - val_acc: 0.4419
Epoch 20/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.3823 - acc: 0.5353Epoch 00020: val_loss improved from 8.04874 to 8.02636, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 254us/step - loss: 7.3811 - acc: 0.5353 - val_loss: 8.0264 - val_acc: 0.4443
Out[22]:
<keras.callbacks.History at 0x7f0ee994e828>

Load the Model with the Best Validation Loss

In [23]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [24]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 44.7368%

Predict Dog Breed with the Model

In [25]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras. These are already in the workspace, at /data/bottleneck_features. If you wish to download them on a different machine, they can be found at:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception.

The above architectures are downloaded and stored for you in the /data/bottleneck_features/ folder.

This means the following will be in the /data/bottleneck_features/ folder:

DogVGG19Data.npz DogResnet50Data.npz DogInceptionV3Data.npz DogXceptionData.npz

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('/data/bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [26]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load('/data/bottleneck_features/DogVGG19Data.npz')
train_VGG19 = bottleneck_features['train']
valid_VGG19 = bottleneck_features['valid']
test_VGG19 = bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

This is one of the four main cases of using the transfer learning approach. In the problem we're tyring to solve, this is the case where our data set is small and similar to original training data. Due to this scenario, I simply sliced off the end of the neural network, and added a new fully connected layer that matches the number of classes in the new data set (133 dog breeds). The weights of the new fully connected layer was randomized, where all the weights from the original (pre-trained) network were held constant to avoid overfitting on the small data set, and the network was trained to update the weights of the new fully connected layer. To detect addtional patterns for the images in our dataset, another fully connected layer with 512 nodes was added (with relu activation). I also included the Dropout layer to further reduce the overfitting problem.

In [27]:
### TODO: Define your architecture.


VGG19_breed_model = Sequential()
VGG19_breed_model.add(GlobalAveragePooling2D(input_shape=train_VGG19.shape[1:]))
VGG19_breed_model.add(Dense(512, activation='relu'))
VGG19_breed_model.add(Dropout(0.3))
VGG19_breed_model.add(Dense(133, activation='softmax'))


VGG19_breed_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 512)               0         
_________________________________________________________________
dense_4 (Dense)              (None, 512)               262656    
_________________________________________________________________
dropout_3 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               68229     
=================================================================
Total params: 330,885
Trainable params: 330,885
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [28]:
### TODO: Compile the model.

VGG19_breed_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [29]:
### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG19.hdf5', 
                               verbose=1, save_best_only=True)

VGG19_breed_model.fit(train_VGG19, train_targets, 
          validation_data=(valid_VGG19, valid_targets),
          epochs=50, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.7156 - acc: 0.3134Epoch 00001: val_loss improved from inf to 1.31138, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 356us/step - loss: 4.7073 - acc: 0.3139 - val_loss: 1.3114 - val_acc: 0.6311
Epoch 2/50
6520/6680 [============================>.] - ETA: 0s - loss: 1.4421 - acc: 0.6288Epoch 00002: val_loss improved from 1.31138 to 1.18318, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 302us/step - loss: 1.4536 - acc: 0.6280 - val_loss: 1.1832 - val_acc: 0.6790
Epoch 3/50
6540/6680 [============================>.] - ETA: 0s - loss: 1.0535 - acc: 0.7301Epoch 00003: val_loss improved from 1.18318 to 1.09934, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 304us/step - loss: 1.0584 - acc: 0.7293 - val_loss: 1.0993 - val_acc: 0.7198
Epoch 4/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.9040 - acc: 0.7739Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 2s 303us/step - loss: 0.9043 - acc: 0.7751 - val_loss: 1.1134 - val_acc: 0.7425
Epoch 5/50
6500/6680 [============================>.] - ETA: 0s - loss: 0.7733 - acc: 0.8008Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 2s 303us/step - loss: 0.7751 - acc: 0.8013 - val_loss: 1.3133 - val_acc: 0.7377
Epoch 6/50
6500/6680 [============================>.] - ETA: 0s - loss: 0.6861 - acc: 0.8362Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 2s 304us/step - loss: 0.6832 - acc: 0.8365 - val_loss: 1.2557 - val_acc: 0.7353
Epoch 7/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.6171 - acc: 0.8495Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 2s 307us/step - loss: 0.6202 - acc: 0.8490 - val_loss: 1.3314 - val_acc: 0.7461
Epoch 8/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.5624 - acc: 0.8677Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s 303us/step - loss: 0.5626 - acc: 0.8678 - val_loss: 1.2895 - val_acc: 0.7701
Epoch 9/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.5978 - acc: 0.8694Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 299us/step - loss: 0.5966 - acc: 0.8699 - val_loss: 1.3646 - val_acc: 0.7677
Epoch 10/50
6500/6680 [============================>.] - ETA: 0s - loss: 0.5189 - acc: 0.8895Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 2s 298us/step - loss: 0.5206 - acc: 0.8897 - val_loss: 1.5347 - val_acc: 0.7689
Epoch 11/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.5098 - acc: 0.8908Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s 299us/step - loss: 0.5113 - acc: 0.8907 - val_loss: 1.6919 - val_acc: 0.7533
Epoch 12/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.4908 - acc: 0.8920Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 2s 299us/step - loss: 0.4933 - acc: 0.8916 - val_loss: 1.6303 - val_acc: 0.7713
Epoch 13/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.4883 - acc: 0.8991Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 301us/step - loss: 0.4893 - acc: 0.8994 - val_loss: 1.6466 - val_acc: 0.7689
Epoch 14/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.4242 - acc: 0.9086Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 0.4234 - acc: 0.9091 - val_loss: 1.8104 - val_acc: 0.7533
Epoch 15/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.4449 - acc: 0.9107Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 0.4475 - acc: 0.9106 - val_loss: 1.6013 - val_acc: 0.7725
Epoch 16/50
6540/6680 [============================>.] - ETA: 0s - loss: 0.3635 - acc: 0.9223Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 298us/step - loss: 0.3648 - acc: 0.9219 - val_loss: 1.8006 - val_acc: 0.7653
Epoch 17/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.3966 - acc: 0.9225Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 299us/step - loss: 0.3992 - acc: 0.9220 - val_loss: 1.8964 - val_acc: 0.7593
Epoch 18/50
6520/6680 [============================>.] - ETA: 0s - loss: 0.3774 - acc: 0.9261Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 0.3802 - acc: 0.9256 - val_loss: 1.9396 - val_acc: 0.7557
Epoch 19/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.3886 - acc: 0.9242Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s 298us/step - loss: 0.3866 - acc: 0.9246 - val_loss: 1.6848 - val_acc: 0.7964
Epoch 20/50
6480/6680 [============================>.] - ETA: 0s - loss: 0.3886 - acc: 0.9285Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 0.3870 - acc: 0.9290 - val_loss: 1.8051 - val_acc: 0.7796
Epoch 21/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.3747 - acc: 0.9322Epoch 00021: val_loss did not improve
6680/6680 [==============================] - 2s 303us/step - loss: 0.3737 - acc: 0.9326 - val_loss: 1.9994 - val_acc: 0.7689
Epoch 22/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.3449 - acc: 0.9384Epoch 00022: val_loss did not improve
6680/6680 [==============================] - 2s 307us/step - loss: 0.3480 - acc: 0.9382 - val_loss: 2.0208 - val_acc: 0.7808
Epoch 23/50
6500/6680 [============================>.] - ETA: 0s - loss: 0.3485 - acc: 0.9385Epoch 00023: val_loss did not improve
6680/6680 [==============================] - 2s 305us/step - loss: 0.3448 - acc: 0.9389 - val_loss: 1.9394 - val_acc: 0.7772
Epoch 24/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.3969 - acc: 0.9312Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 0.3981 - acc: 0.9313 - val_loss: 1.9835 - val_acc: 0.7689
Epoch 25/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.3539 - acc: 0.9413Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 2s 297us/step - loss: 0.3531 - acc: 0.9415 - val_loss: 2.0311 - val_acc: 0.7713
Epoch 26/50
6520/6680 [============================>.] - ETA: 0s - loss: 0.3522 - acc: 0.9374Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 2s 298us/step - loss: 0.3530 - acc: 0.9376 - val_loss: 1.9390 - val_acc: 0.7772
Epoch 27/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.3311 - acc: 0.9405Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 2s 298us/step - loss: 0.3297 - acc: 0.9406 - val_loss: 1.9311 - val_acc: 0.7928
Epoch 28/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.3591 - acc: 0.9375Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 2s 299us/step - loss: 0.3578 - acc: 0.9374 - val_loss: 1.8103 - val_acc: 0.7928
Epoch 29/50
6500/6680 [============================>.] - ETA: 0s - loss: 0.3187 - acc: 0.9477Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 2s 301us/step - loss: 0.3191 - acc: 0.9475 - val_loss: 2.1663 - val_acc: 0.7725
Epoch 30/50
6520/6680 [============================>.] - ETA: 0s - loss: 0.3154 - acc: 0.9491Epoch 00030: val_loss did not improve
6680/6680 [==============================] - 2s 305us/step - loss: 0.3127 - acc: 0.9493 - val_loss: 2.0602 - val_acc: 0.7701
Epoch 31/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.3013 - acc: 0.9474Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 2s 308us/step - loss: 0.3020 - acc: 0.9473 - val_loss: 2.1377 - val_acc: 0.7832
Epoch 32/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.3112 - acc: 0.9474Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 2s 303us/step - loss: 0.3103 - acc: 0.9476 - val_loss: 2.1386 - val_acc: 0.7725
Epoch 33/50
6520/6680 [============================>.] - ETA: 0s - loss: 0.3037 - acc: 0.9517Epoch 00033: val_loss did not improve
6680/6680 [==============================] - 2s 302us/step - loss: 0.3065 - acc: 0.9516 - val_loss: 2.1825 - val_acc: 0.7868
Epoch 34/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.3087 - acc: 0.9477Epoch 00034: val_loss did not improve
6680/6680 [==============================] - 2s 307us/step - loss: 0.3105 - acc: 0.9476 - val_loss: 2.2845 - val_acc: 0.7629
Epoch 35/50
6540/6680 [============================>.] - ETA: 0s - loss: 0.3117 - acc: 0.9511Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 2s 305us/step - loss: 0.3147 - acc: 0.9507 - val_loss: 2.3095 - val_acc: 0.7701
Epoch 36/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.3016 - acc: 0.9500Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 2s 304us/step - loss: 0.3010 - acc: 0.9500 - val_loss: 2.3826 - val_acc: 0.7701
Epoch 37/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.3137 - acc: 0.9532Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 2s 305us/step - loss: 0.3080 - acc: 0.9540 - val_loss: 2.2926 - val_acc: 0.7725
Epoch 38/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.3387 - acc: 0.9500Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 2s 301us/step - loss: 0.3450 - acc: 0.9496 - val_loss: 2.3356 - val_acc: 0.7713
Epoch 39/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.3070 - acc: 0.9544Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 2s 305us/step - loss: 0.3052 - acc: 0.9546 - val_loss: 2.2675 - val_acc: 0.7832
Epoch 40/50
6520/6680 [============================>.] - ETA: 0s - loss: 0.2877 - acc: 0.9555Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 2s 311us/step - loss: 0.2950 - acc: 0.9546 - val_loss: 2.0742 - val_acc: 0.7808
Epoch 41/50
6500/6680 [============================>.] - ETA: 0s - loss: 0.2943 - acc: 0.9555Epoch 00041: val_loss did not improve
6680/6680 [==============================] - 2s 314us/step - loss: 0.2932 - acc: 0.9555 - val_loss: 2.1627 - val_acc: 0.7808
Epoch 42/50
6500/6680 [============================>.] - ETA: 0s - loss: 0.3024 - acc: 0.9575Epoch 00042: val_loss did not improve
6680/6680 [==============================] - 2s 313us/step - loss: 0.3007 - acc: 0.9575 - val_loss: 2.2209 - val_acc: 0.7749
Epoch 43/50
6500/6680 [============================>.] - ETA: 0s - loss: 0.3162 - acc: 0.9546Epoch 00043: val_loss did not improve
6680/6680 [==============================] - 2s 314us/step - loss: 0.3204 - acc: 0.9540 - val_loss: 2.3599 - val_acc: 0.7701
Epoch 44/50
6500/6680 [============================>.] - ETA: 0s - loss: 0.2813 - acc: 0.9597Epoch 00044: val_loss did not improve
6680/6680 [==============================] - 2s 315us/step - loss: 0.2782 - acc: 0.9599 - val_loss: 2.3660 - val_acc: 0.7808
Epoch 45/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.2765 - acc: 0.9608Epoch 00045: val_loss did not improve
6680/6680 [==============================] - 2s 304us/step - loss: 0.2746 - acc: 0.9612 - val_loss: 2.2405 - val_acc: 0.7940
Epoch 46/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.3013 - acc: 0.9586Epoch 00046: val_loss did not improve
6680/6680 [==============================] - 2s 307us/step - loss: 0.3016 - acc: 0.9587 - val_loss: 2.2846 - val_acc: 0.7629
Epoch 47/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.2938 - acc: 0.9555Epoch 00047: val_loss did not improve
6680/6680 [==============================] - 2s 304us/step - loss: 0.2930 - acc: 0.9552 - val_loss: 2.4626 - val_acc: 0.7772
Epoch 48/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.2838 - acc: 0.9594Epoch 00048: val_loss did not improve
6680/6680 [==============================] - 2s 307us/step - loss: 0.2841 - acc: 0.9596 - val_loss: 2.3457 - val_acc: 0.7784
Epoch 49/50
6520/6680 [============================>.] - ETA: 0s - loss: 0.3330 - acc: 0.9544Epoch 00049: val_loss did not improve
6680/6680 [==============================] - 2s 313us/step - loss: 0.3307 - acc: 0.9549 - val_loss: 2.3743 - val_acc: 0.7964
Epoch 50/50
6500/6680 [============================>.] - ETA: 0s - loss: 0.2919 - acc: 0.9578Epoch 00050: val_loss did not improve
6680/6680 [==============================] - 2s 310us/step - loss: 0.2964 - acc: 0.9578 - val_loss: 2.3789 - val_acc: 0.7772
Out[29]:
<keras.callbacks.History at 0x7f0ee8616940>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [30]:
### TODO: Load the model weights with the best validation loss.
VGG19_breed_model.load_weights('saved_models/weights.best.VGG19.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [31]:
### TODO: Calculate classification accuracy on the test dataset.

VGG19_breed_predictions = [np.argmax(VGG19_breed_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG19]

test_accuracy = 100*np.sum(np.array(VGG19_breed_predictions)==np.argmax(test_targets, axis=1))/len(VGG19_breed_predictions)

print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 71.4115%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [32]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.


def predicted_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG19(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG19_breed_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [33]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def display_image(img_path):
    img = cv2.imread(img_path)
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    imgplot = plt.imshow(cv_rgb)
    return imgplot

def detect_image(img_path):
    
    # display the image 
    display_image(img_path)
    
    # if a dog is detected, return the predicted breed.  
    if dog_detector(img_path):
        return "Cute doggie alert! Your predicted breed is {}. Woof Woof!!!".format(predicted_breed(img_path))
    
    #if a face is detected, return the resembling dog breed
    elif face_detector(img_path):
        return "Hello there, Homo sapien! Your resembling dog breed is {}".format(predicted_breed(img_path))
    
    # return error otherwise
    else:
        return "OH NOOO!!! Cannot detect a pawsome face in the image! Neither a hooman nor a doggie. Possibly a cute alien??? "
In [34]:
from IPython.display import Image
Image(filename='images/khai_images/bulldogies.jpg')
Out[34]:
In [35]:
Image(filename='images/khai_images/kirill_me.jpg')
Out[35]:

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

It is better than I expected. To improve my current model in the future, I will consider the following points. (1) I will use a different optimizer, such as SGD+momentum. (2) Since we're using the pre-trained model, I will also lower the learning rate, less than 10^-3. (3) Generating more images using the data augmentaiton for the training proccess will also be helpful. (4) I would also consider adding batch normalization layers to improve the performance. (5) Lastly, it's worthwhile to apply the ensemble method, where various pre-trained CNN models can be levereged to compose muliple CNNs into ensembles using different learning rates, batch sizes, and other features.

In [36]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
In [ ]:

In [37]:
detect_image('images/khai_images/bulldogies.jpg')
Out[37]:
'Cute doggie alert! Your predicted breed is in/040.Bulldog. Woof Woof!!!'
In [38]:
detect_image('images/khai_images/kirill_me.jpg')
Out[38]:
'Hello there, Homo sapien! Your resembling dog breed is in/124.Poodle'

I know there were 2 people in the above picture and it is unclear which person resembles to Dachshund in this example. In the future, we should add additional features to our app where it should produce the corresponding # of resembling breeds based on the # of faces detected in the image.

In [39]:
detect_image('images/khai_images/dan.jpg')
Out[39]:
'Hello there, Homo sapien! Your resembling dog breed is in/091.Japanese_chin'
In [40]:
detect_image('images/khai_images/me.jpg')
Out[40]:
'Hello there, Homo sapien! Your resembling dog breed is in/006.American_eskimo_dog'
In [41]:
detect_image('images/khai_images/Kristen.jpg')
Out[41]:
'Hello there, Homo sapien! Your resembling dog breed is in/132.Xoloitzcuintli'
In [42]:
detect_image('images/khai_images/hp.jpg')
Out[42]:
'Hello there, Homo sapien! Your resembling dog breed is in/011.Australian_cattle_dog'
In [43]:
detect_image('images/khai_images/hadelin.png')
Out[43]:
'Hello there, Homo sapien! Your resembling dog breed is in/116.Parson_russell_terrier'
In [44]:
detect_image('images/khai_images/kirill2.png')
Out[44]:
'Hello there, Homo sapien! Your resembling dog breed is in/045.Cardigan_welsh_corgi'
In [45]:
detect_image('images/khai_images/bumble_bee.jpg')
Out[45]:
'OH NOOO!!! Cannot detect a pawsome face in the image! Neither a hooman nor a doggie. Possibly a cute alien??? '
In [46]:
detect_image('images/khai_images/aus_shepherd.jpg')
Out[46]:
'Cute doggie alert! Your predicted breed is in/012.Australian_shepherd. Woof Woof!!!'
In [47]:
detect_image('images/khai_images/petey_vic.jpg')
Out[47]:
'Cute doggie alert! Your predicted breed is in/034.Boxer. Woof Woof!!!'
In [48]:
detect_image('images/khai_images/petey_iri.jpg')
Out[48]:
'Cute doggie alert! Your predicted breed is in/045.Cardigan_welsh_corgi. Woof Woof!!!'
In [49]:
detect_image('images/khai_images/ben_taylor.png')
Out[49]:
'Hello there, Homo sapien! Your resembling dog breed is in/014.Basenji'
In [50]:
detect_image('images/khai_images/eric_webber.png')
Out[50]:
'Cute doggie alert! Your predicted breed is in/010.Anatolian_shepherd_dog. Woof Woof!!!'
In [51]:
detect_image('images/khai_images/debbie_berebichez.png')
Out[51]:
'Hello there, Homo sapien! Your resembling dog breed is in/060.Dogue_de_bordeaux'
In [52]:
detect_image('images/khai_images/venom.png')
Out[52]:
'OH NOOO!!! Cannot detect a pawsome face in the image! Neither a hooman nor a doggie. Possibly a cute alien??? '
In [53]:
detect_image('images/khai_images/kai_chung.png')
Out[53]:
'Hello there, Homo sapien! Your resembling dog breed is in/045.Cardigan_welsh_corgi'
In [54]:
detect_image('images/khai_images/xmas_tree.jpg')
Out[54]:
'OH NOOO!!! Cannot detect a pawsome face in the image! Neither a hooman nor a doggie. Possibly a cute alien??? '
In [55]:
detect_image('images/khai_images/kenso_trabing.png')
Out[55]:
'Hello there, Homo sapien! Your resembling dog breed is in/014.Basenji'
In [56]:
detect_image('images/khai_images/rum.png')
Out[56]:
'Hello there, Homo sapien! Your resembling dog breed is in/008.American_staffordshire_terrier'
In [ ]:
 

I also tried the same process using another pre-trained model.

In [57]:
### TODO: Obtain bottleneck features from another pre-trained CNN.

bottleneck_features = np.load('/data/bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features['train']
valid_Xception = bottleneck_features['valid']
test_Xception = bottleneck_features['test']



### TODO: Define your architecture.

Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
Xception_model.add(Dense(512, activation='relu'))
Xception_model.add(Dropout(0.4))
Xception_model.add(Dense(133, activation='softmax'))

Xception_model.summary()


### TODO: Compile the model.
Xception_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 2048)              0         
_________________________________________________________________
dense_6 (Dense)              (None, 512)               1049088   
_________________________________________________________________
dropout_4 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_7 (Dense)              (None, 133)               68229     
=================================================================
Total params: 1,117,317
Trainable params: 1,117,317
Non-trainable params: 0
_________________________________________________________________
In [58]:
### TODO: Train the model.
from keras.callbacks import ModelCheckpoint 

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Xception.hdf5', 
                               verbose=1, save_best_only=True)

Xception_model.fit(train_Xception, train_targets, 
          validation_data=(valid_Xception, valid_targets),
          epochs=50, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/50
6640/6680 [============================>.] - ETA: 0s - loss: 1.4629 - acc: 0.6435Epoch 00001: val_loss improved from inf to 0.61564, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 4s 657us/step - loss: 1.4587 - acc: 0.6448 - val_loss: 0.6156 - val_acc: 0.8000
Epoch 2/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.6499 - acc: 0.8050Epoch 00002: val_loss improved from 0.61564 to 0.58757, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s 523us/step - loss: 0.6501 - acc: 0.8048 - val_loss: 0.5876 - val_acc: 0.8228
Epoch 3/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.5205 - acc: 0.8397Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 4s 619us/step - loss: 0.5177 - acc: 0.8406 - val_loss: 0.6698 - val_acc: 0.8084
Epoch 4/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.4434 - acc: 0.8620Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 3s 515us/step - loss: 0.4463 - acc: 0.8618 - val_loss: 0.6977 - val_acc: 0.8240
Epoch 5/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.3864 - acc: 0.8804Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 3s 520us/step - loss: 0.3879 - acc: 0.8807 - val_loss: 0.6038 - val_acc: 0.8263
Epoch 6/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.3404 - acc: 0.8961Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 3s 517us/step - loss: 0.3411 - acc: 0.8964 - val_loss: 0.6426 - val_acc: 0.8455
Epoch 7/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.3067 - acc: 0.9060Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 3s 521us/step - loss: 0.3076 - acc: 0.9057 - val_loss: 0.6882 - val_acc: 0.8371
Epoch 8/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.2676 - acc: 0.9200Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 4s 562us/step - loss: 0.2688 - acc: 0.9199 - val_loss: 0.6770 - val_acc: 0.8395
Epoch 9/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.2593 - acc: 0.9219Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 4s 552us/step - loss: 0.2598 - acc: 0.9219 - val_loss: 0.6990 - val_acc: 0.8371
Epoch 10/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.2366 - acc: 0.9249Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 4s 525us/step - loss: 0.2344 - acc: 0.9256 - val_loss: 0.7742 - val_acc: 0.8323
Epoch 11/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.2093 - acc: 0.9369Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 3s 513us/step - loss: 0.2101 - acc: 0.9370 - val_loss: 0.8360 - val_acc: 0.8395
Epoch 12/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.2081 - acc: 0.9354Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 3s 491us/step - loss: 0.2102 - acc: 0.9350 - val_loss: 0.7753 - val_acc: 0.8539
Epoch 13/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.1913 - acc: 0.9444Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 3s 497us/step - loss: 0.1924 - acc: 0.9443 - val_loss: 0.8297 - val_acc: 0.8479
Epoch 14/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.1736 - acc: 0.9488Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 3s 489us/step - loss: 0.1738 - acc: 0.9485 - val_loss: 0.9029 - val_acc: 0.8395
Epoch 15/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.1762 - acc: 0.9474Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 3s 509us/step - loss: 0.1766 - acc: 0.9472 - val_loss: 0.9083 - val_acc: 0.8443
Epoch 16/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.1659 - acc: 0.9527Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 3s 510us/step - loss: 0.1663 - acc: 0.9522 - val_loss: 0.8901 - val_acc: 0.8455
Epoch 17/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.1602 - acc: 0.9514Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 4s 529us/step - loss: 0.1599 - acc: 0.9513 - val_loss: 0.8662 - val_acc: 0.8491
Epoch 18/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.1320 - acc: 0.9594Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 4s 530us/step - loss: 0.1333 - acc: 0.9591 - val_loss: 0.9391 - val_acc: 0.8503
Epoch 19/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.1339 - acc: 0.9650Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 4s 533us/step - loss: 0.1341 - acc: 0.9648 - val_loss: 1.0464 - val_acc: 0.8383
Epoch 20/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.1346 - acc: 0.9617Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 4s 535us/step - loss: 0.1364 - acc: 0.9615 - val_loss: 1.0553 - val_acc: 0.8323
Epoch 21/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.1259 - acc: 0.9643Epoch 00021: val_loss did not improve
6680/6680 [==============================] - 4s 535us/step - loss: 0.1252 - acc: 0.9645 - val_loss: 0.9573 - val_acc: 0.8431
Epoch 22/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.1238 - acc: 0.9639Epoch 00022: val_loss did not improve
6680/6680 [==============================] - 4s 540us/step - loss: 0.1227 - acc: 0.9642 - val_loss: 1.0490 - val_acc: 0.8419
Epoch 23/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.0983 - acc: 0.9684Epoch 00023: val_loss did not improve
6680/6680 [==============================] - 4s 535us/step - loss: 0.0978 - acc: 0.9684 - val_loss: 0.9904 - val_acc: 0.8455
Epoch 24/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.1257 - acc: 0.9684Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 3s 518us/step - loss: 0.1252 - acc: 0.9684 - val_loss: 1.0962 - val_acc: 0.8527
Epoch 25/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.1165 - acc: 0.9656Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 3s 519us/step - loss: 0.1162 - acc: 0.9657 - val_loss: 1.0809 - val_acc: 0.8467
Epoch 26/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.1113 - acc: 0.9699Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 3s 515us/step - loss: 0.1117 - acc: 0.9696 - val_loss: 1.1192 - val_acc: 0.8587
Epoch 27/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.1056 - acc: 0.9707Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 3s 520us/step - loss: 0.1050 - acc: 0.9708 - val_loss: 1.0952 - val_acc: 0.8335
Epoch 28/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.1019 - acc: 0.9718Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 3s 515us/step - loss: 0.1029 - acc: 0.9717 - val_loss: 1.1193 - val_acc: 0.8491
Epoch 29/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.1184 - acc: 0.9701Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 3s 523us/step - loss: 0.1184 - acc: 0.9701 - val_loss: 1.1560 - val_acc: 0.8383
Epoch 30/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.0951 - acc: 0.9734Epoch 00030: val_loss did not improve
6680/6680 [==============================] - 3s 523us/step - loss: 0.0948 - acc: 0.9735 - val_loss: 1.1436 - val_acc: 0.8491
Epoch 31/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.0930 - acc: 0.9762Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 3s 508us/step - loss: 0.0940 - acc: 0.9760 - val_loss: 1.2365 - val_acc: 0.8503
Epoch 32/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.0900 - acc: 0.9754Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 4s 529us/step - loss: 0.0897 - acc: 0.9754 - val_loss: 1.1918 - val_acc: 0.8527
Epoch 33/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.1021 - acc: 0.9744Epoch 00033: val_loss did not improve
6680/6680 [==============================] - 3s 518us/step - loss: 0.1010 - acc: 0.9747 - val_loss: 1.3408 - val_acc: 0.8443
Epoch 34/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.0919 - acc: 0.9761Epoch 00034: val_loss did not improve
6680/6680 [==============================] - 3s 502us/step - loss: 0.0923 - acc: 0.9757 - val_loss: 1.2120 - val_acc: 0.8335
Epoch 35/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.0906 - acc: 0.9758Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 3s 494us/step - loss: 0.0900 - acc: 0.9759 - val_loss: 1.1778 - val_acc: 0.8551
Epoch 36/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.0963 - acc: 0.9764Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 3s 489us/step - loss: 0.0961 - acc: 0.9763 - val_loss: 1.3054 - val_acc: 0.8407
Epoch 37/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.0823 - acc: 0.9789Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 3s 495us/step - loss: 0.0826 - acc: 0.9789 - val_loss: 1.3098 - val_acc: 0.8443
Epoch 38/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.0827 - acc: 0.9798Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 3s 498us/step - loss: 0.0828 - acc: 0.9798 - val_loss: 1.3163 - val_acc: 0.8431
Epoch 39/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.0820 - acc: 0.9780Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 4s 539us/step - loss: 0.0833 - acc: 0.9772 - val_loss: 1.3318 - val_acc: 0.8455
Epoch 40/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.0827 - acc: 0.9780Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 4s 540us/step - loss: 0.0831 - acc: 0.9778 - val_loss: 1.3919 - val_acc: 0.8419
Epoch 41/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.0870 - acc: 0.9793Epoch 00041: val_loss did not improve
6680/6680 [==============================] - 3s 521us/step - loss: 0.0887 - acc: 0.9793 - val_loss: 1.2505 - val_acc: 0.8419
Epoch 42/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.0765 - acc: 0.9805Epoch 00042: val_loss did not improve
6680/6680 [==============================] - 4s 530us/step - loss: 0.0764 - acc: 0.9805 - val_loss: 1.2802 - val_acc: 0.8431
Epoch 43/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.0734 - acc: 0.9826Epoch 00043: val_loss did not improve
6680/6680 [==============================] - 4s 528us/step - loss: 0.0727 - acc: 0.9828 - val_loss: 1.2210 - val_acc: 0.8503
Epoch 44/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.0936 - acc: 0.9795Epoch 00044: val_loss did not improve
6680/6680 [==============================] - 3s 486us/step - loss: 0.0937 - acc: 0.9793 - val_loss: 1.2600 - val_acc: 0.8443
Epoch 45/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.0774 - acc: 0.9820Epoch 00045: val_loss did not improve
6680/6680 [==============================] - 3s 484us/step - loss: 0.0783 - acc: 0.9820 - val_loss: 1.2583 - val_acc: 0.8539
Epoch 46/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.0756 - acc: 0.9823Epoch 00046: val_loss did not improve
6680/6680 [==============================] - 3s 485us/step - loss: 0.0752 - acc: 0.9822 - val_loss: 1.3026 - val_acc: 0.8467
Epoch 47/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.0749 - acc: 0.9819Epoch 00047: val_loss did not improve
6680/6680 [==============================] - 4s 528us/step - loss: 0.0752 - acc: 0.9817 - val_loss: 1.3711 - val_acc: 0.8407
Epoch 48/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.0686 - acc: 0.9831Epoch 00048: val_loss did not improve
6680/6680 [==============================] - 3s 522us/step - loss: 0.0681 - acc: 0.9832 - val_loss: 1.3226 - val_acc: 0.8491
Epoch 49/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.0685 - acc: 0.9846Epoch 00049: val_loss did not improve
6680/6680 [==============================] - 4s 528us/step - loss: 0.0679 - acc: 0.9847 - val_loss: 1.4046 - val_acc: 0.8515
Epoch 50/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.0840 - acc: 0.9829Epoch 00050: val_loss did not improve
6680/6680 [==============================] - 4s 530us/step - loss: 0.0832 - acc: 0.9829 - val_loss: 1.4698 - val_acc: 0.8359
Out[58]:
<keras.callbacks.History at 0x7f0ec0437668>
In [59]:
### TODO: Load the model weights with the best validation loss.
Xception_model.load_weights('saved_models/weights.best.Xception.hdf5')
In [60]:
### TODO: Calculate classification accuracy on the test dataset.
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]
test_accuracy = 100*np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/len(Xception_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 81.1005%

Using the Xception, the accuracy improved to ~82% compared to VGG19 model that was used earlier (~74%).

In [61]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

def Xception_predict_breed(img_path):
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))     # extract bottleneck features
    predicted_vector = Xception_model.predict(bottleneck_feature)       # obtain predicted vector
    return dog_names[np.argmax(predicted_vector)]                       # return dog breed that is predicted by the model
In [62]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def display_image(img_path):
    img = cv2.imread(img_path)
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    imgplot = plt.imshow(cv_rgb)
    return imgplot

def detect_image(img_path):
    
    # display the image 
    display_image(img_path)
    
    # if a dog is detected, return the predicted breed.  
    if dog_detector(img_path):
        return "Cute doggie alert! Your predicted breed is {}. Woof Woof!!!".format(predicted_breed(img_path))
    
    #if a face is detected, return the resembling dog breed
    elif face_detector(img_path):
        return "Hello there, Homo sapien! Your resembling dog breed is {}".format(predicted_breed(img_path))
    
    # return error otherwise
    else:
        return "OH NOOO!!! Cannot detect a pawsome face in the image! Neither a hooman nor a doggie. Possibly a cute alien??? "
In [63]:
detect_image('images/khai_images/bulldogies.jpg')
Out[63]:
'Cute doggie alert! Your predicted breed is in/040.Bulldog. Woof Woof!!!'

When I ran this model before, the model predicted the boxer as the breed. It's understandable since they can be very much alike, especially as puppies.

In [64]:
detect_image('images/khai_images/aus_shepherd.jpg')
Out[64]:
'Cute doggie alert! Your predicted breed is in/012.Australian_shepherd. Woof Woof!!!'
In [65]:
detect_image('images/khai_images/bumble_bee.jpg')
Out[65]:
'OH NOOO!!! Cannot detect a pawsome face in the image! Neither a hooman nor a doggie. Possibly a cute alien??? '
In [66]:
detect_image('images/khai_images/petey_iri.jpg')
Out[66]:
'Cute doggie alert! Your predicted breed is in/045.Cardigan_welsh_corgi. Woof Woof!!!'
In [67]:
detect_image('images/khai_images/iri.jpg')
Out[67]:
'Cute doggie alert! Your predicted breed is in/034.Boxer. Woof Woof!!!'
In [68]:
detect_image('images/khai_images/shoe.jpg')
Out[68]:
'OH NOOO!!! Cannot detect a pawsome face in the image! Neither a hooman nor a doggie. Possibly a cute alien??? '
In [69]:
detect_image('images/khai_images/dan.jpg')
Out[69]:
'Hello there, Homo sapien! Your resembling dog breed is in/091.Japanese_chin'
In [70]:
detect_image('images/khai_images/hadelin.png')
Out[70]:
'Hello there, Homo sapien! Your resembling dog breed is in/116.Parson_russell_terrier'
In [71]:
detect_image('images/khai_images/ben_taylor.png')
Out[71]:
'Hello there, Homo sapien! Your resembling dog breed is in/014.Basenji'
In [72]:
detect_image('images/khai_images/kirill2.png')
Out[72]:
'Hello there, Homo sapien! Your resembling dog breed is in/045.Cardigan_welsh_corgi'
In [73]:
detect_image('images/khai_images/debbie_berebichez.png')
Out[73]:
'Hello there, Homo sapien! Your resembling dog breed is in/060.Dogue_de_bordeaux'
In [74]:
detect_image('images/khai_images/venom.png')
Out[74]:
'OH NOOO!!! Cannot detect a pawsome face in the image! Neither a hooman nor a doggie. Possibly a cute alien??? '
In [75]:
detect_image('images/khai_images/kenso_trabing.png')
Out[75]:
'Hello there, Homo sapien! Your resembling dog breed is in/014.Basenji'
In [76]:
detect_image('images/khai_images/me3.png')
Out[76]:
'Hello there, Homo sapien! Your resembling dog breed is in/044.Cane_corso'
In [77]:
detect_image('images/khai_images/kai_chung.png')
Out[77]:
'Hello there, Homo sapien! Your resembling dog breed is in/045.Cardigan_welsh_corgi'

Had sooo much fun doing this project! Woof Woof!!!

Please download your notebook to submit

In order to submit, please do the following:

  1. Download an HTML version of the notebook to your computer using 'File: Download as...'
  2. Click on the orange Jupyter circle on the top left of the workspace.
  3. Navigate into the dog-project folder to ensure that you are using the provided dog_images, lfw, and bottleneck_features folders; this means that those folders will not appear in the dog-project folder. If they do appear because you downloaded them, delete them.
  4. While in the dog-project folder, upload the HTML version of this notebook you just downloaded. The upload button is on the top right.
  5. Navigate back to the home folder by clicking on the two dots next to the folder icon, and then open up a terminal under the 'new' tab on the top right
  6. Zip the dog-project folder with the following command in the terminal: zip -r dog-project.zip dog-project
  7. Download the zip file by clicking on the square next to it and selecting 'download'. This will be the zip file you turn in on the next node after this workspace!
In [ ]: